package net.zjitc.servlet.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2020/5/15 8:30
 **/
@WebServlet("/requestDemo3")
public class RequestDemo3 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* request对象功能：
           3、获取请求体数据 （post请求才有请求体）
              获取输入流对象（字符/字节）*/
       /* BufferedReader br = req.getReader();
        String line=null;
        while ((line=br.readLine())!=null){
            System.out.println(line);
        }
        if(br!=null){
            br.close();
        }*/

        /* 4、获取请求参数
        *     get请求的请求参数在url里 https://baidu.com/2.html?name='pan'
        *     post请求的请求参数在请求体里*/


        /* 获取单个值的参数*/
        String username = req.getParameter("username");
        /* 获取所有参数 保存在Map*/
        Map<String, String[]> parameterMap = req.getParameterMap();
        /* 获取有多个值的参数*/
        String[] hobbies = req.getParameterValues("hobby");

        System.out.println("username: "+username);
        System.out.println("hobby: ");
        for (int i = 0; i <hobbies.length ; i++) {
            System.out.println(hobbies[i]);
        }
        System.out.println("所有的请求参数Map:");
        Iterator<String> iterator = parameterMap.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            String[] values = parameterMap.get(key);
            System.out.println(key+": ");
            for (String s:values) {
                System.out.println(s);
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
